package com.sxbbc.api.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.sxbbc.common.core.dto.jz.*;
import com.sxbbc.common.core.entity.jz.*;
import com.sxbbc.common.core.enums.*;
import com.sxbbc.common.core.mapper.jz.*;
import com.sxbbc.common.core.service.*;

import com.sxbbc.common.core.service.system.mode.ModeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.function.common.GetRest;
import com.function.common.RestResponse;
import com.sxbbc.api.service.IBusinessService;
import com.sxbbc.api.service.IOrderService;
import com.sxbbc.common.basics.exceptions.ThrowJsonException;
import com.sxbbc.common.basics.utils.calculation.CalcuUtils;
import com.sxbbc.common.basics.utils.date.DateUtil;
import com.sxbbc.common.basics.utils.statics.StaticUtils;
import com.sxbbc.common.core.utils.BasePage;

/**
 * 订单数据显示 业务处理实现类
 *
 * @author xiaoky
 * @date 2019-05-25
 */
@Service
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private OrderMainMapper orderMainMapper;
    @Autowired
    private IOrderDetailService orderDetailService;
    @Autowired
    private IOrderExpDetailService orderExpDetailService;
    @Autowired
    private OrderConfigGroupMapper orderConfigGroupMapper;
    @Autowired
    private BBusinessService bBusinessService;
    @Autowired
    private AddressMapper addressMapper;
    @Autowired
    private IOrderMainService orderMainService;
    @Autowired
    private ProcEvaluateMapper procEvaluateMapper;
    @Autowired
    private ChickenCouponMapper chickenCouponMapper;
    @Autowired
    private IOrderDetailService iOrderDetailService;
    @Autowired
    private IInfoShoppingService iInfoShoppingService;
    @Autowired
    private IBusinessService apiBusinessService;
    @Autowired
    private IAccountChangeService accountChangeService;
    @Autowired
    private ModeService modeService;
    @Autowired
    private ICRechageDetailService rechageDetailService;
    @Autowired
    private ChickenLogisticsOrderMapper chickenLogisticsOrderMapper;

    @Override
    public IPage<OrderBaseVo> queryOrder(BasePage<OrderMain> page, OrderMain order) {
        CalcuUtils calcuUtils = CalcuUtils.getInstance();
        IPage<OrderMain> pageInfo = orderMainMapper.queryOrder(page, order);
        List<OrderBaseVo> baseList = new ArrayList<>();
        for (OrderMain o : pageInfo.getRecords()) {
            String statusPrefix = "";
            OrderBaseVo vo = new OrderBaseVo();
            BeanUtils.copyProperties(o, vo);
            if (calcuUtils.isEquals(o.getOrderType(), OrderTypeEnums.NORMAL.getId())) {
                // 订单状态名称后缀
                String statusSuffix = OrderStatusEnums.getName(o.getOrderStatus());
                // 订单状态
                vo.setOrderStatusName(statusPrefix + statusSuffix);
            } else if (calcuUtils.isEquals(o.getOrderType(), OrderTypeEnums.OFFLINE.getId())) {
                // 订单状态名称后缀
                String statusSuffix = OfflineOrderStatusEnums.getName(o.getOrderStatus());
                // 订单状态
                vo.setOrderStatusName(statusPrefix + statusSuffix);
            }
            // 订单详情
            List<OrderDetail> details = orderDetailService.listByOrderCode(o.getOrderCode());
            vo.setDetails(details);
            // 店铺联系信息
            BusinessInfoVo businessMsg = apiBusinessService.queryBusinessLinkMsg(o.getBid());
            vo.setBusinessMsg(businessMsg);
            baseList.add(vo);

        }
        IPage<OrderBaseVo> returnPage = new BasePage<>();
        BeanUtils.copyProperties(page, returnPage);
        returnPage.setRecords(baseList);
        return returnPage;
    }

    @Override
    public OrderDetailVo handleQueryOrderDetailById(Integer orderId) {
        OrderMain order = orderMainMapper.selectById(orderId);
        OrderDetailVo vo = new OrderDetailVo();
        if (order != null) {
            BeanUtils.copyProperties(order, vo);
            // 店铺名称
            BBusiness business = bBusinessService.getById(order.getBid());
            if (business != null) {
                vo.setBNickName(business.getNickNameOn());
            }
            // 订单状态
            vo.setOrderStatusName(OrderStatusEnums.getName(vo.getOrderStatus()));
            // 订单类型
            vo.setOrderType(order.getOrderType());
            vo.setPayTypeName(PayTypeEnums.getName(order.getPayType()));
            // 订单详情
            List<OrderDetail> details = orderDetailService.listByOrderCode(vo.getOrderCode());
            vo.setDetails(details);

            CalcuUtils calcuUtils = CalcuUtils.getInstance();
            if (calcuUtils.isEquals(order.getOrderType(), OrderTypeEnums.NORMAL.getId())) {
                // 待收货状态
                if (CalcuUtils.getInstance().isEquals(order.getOrderStatus(), OrderStatusEnums.HAS_SEND.getId())) {
                    //计算支付截止时间
                    QueryWrapper<InfoShopping> wrapper = new QueryWrapper<>();
                    InfoShopping infoShopping = iInfoShoppingService.getOne(wrapper);
                    Date autoReceiveTime = DateUtil.getInstance().addDate(order.getSendTime(), infoShopping.getAutoReceived());
                    vo.setAutoReceiveTime(autoReceiveTime);
                }
                List<OrderReceivedVo> receivedList = new ArrayList<>();
                QueryWrapper<OrderExpDetail> expWrapper = new QueryWrapper<>();
                expWrapper.eq("order_code", vo.getOrderCode());
                List<OrderExpDetail> expDetailList = orderExpDetailService.list(expWrapper);
                for (OrderExpDetail expDetail : expDetailList) {
                    OrderReceivedVo receivedVo = new OrderReceivedVo();
                    // 物流信息
                    vo.setReceiver(expDetail.getReceiver());
                    vo.setReceiverPhone(expDetail.getPhone());
                    vo.setReceiverAddr(expDetail.getAddrPrefix() + " " + expDetail.getAddressDetail());
                    if (order.getOrderStatus() >= OrderStatusEnums.HAS_SEND.getId()) {
                        receivedVo.setExpId(expDetail.getId());
                        // 最新的物流数据
                        String expMsg = orderExpDetailService.handleLiveExpData(expDetail.getId());
                        // 获取最近的物流时间和物流事件
                        getAcceptExp(receivedVo, expMsg);
                        receivedList.add(receivedVo);
                    }
                }
                vo.setReceivedList(receivedList);
            } else if (calcuUtils.isEquals(order.getOrderType(), OrderTypeEnums.OFFLINE.getId())) {
                if (business != null) {
                    // 地址详情处理(加上省市县)
                    String proName = addressMapper.selectAddressNameById(business.getProId());
                    String cityName = addressMapper.selectAddressNameById(business.getCityId());
                    String areaName = addressMapper.selectAddressNameById(business.getAreaId());
                    vo.setBusinessAddressDetail(proName + " " + cityName + " " + areaName + " " + business.getAddressDetail());
                    vo.setBusLatVal(business.getLatVal());
                    vo.setBusLonVal(business.getLonVal());
                }
            }
            vo.setCancelStatus(StaticUtils.STATUS_NO);
            // 店铺联系信息
            BusinessInfoVo businessMsg = apiBusinessService.queryBusinessLinkMsg(order.getBid());
            vo.setBusinessMsg(businessMsg);
        }
        return vo;
    }

    @Override
    public FarmLogisticsOrderDetailVo handleQueryChickenLogisticsOrderDetailById(Integer orderId) {
        OrderMain order = orderMainMapper.selectById(orderId);
        FarmLogisticsOrderDetailVo vo = new FarmLogisticsOrderDetailVo();
        BeanUtils.copyProperties(order, vo);
        if (order != null) {
            // 店铺名称
            BBusiness business = bBusinessService.getById(order.getBid());
            if (business != null) {
                vo.setBNickName(business.getNickNameOn());
            }
            // 订单状态
            vo.setOrderStatusName(OrderStatusEnums.getName(vo.getOrderStatus()));
            // 订单类型
            vo.setOrderType(order.getOrderType());
            vo.setNum(order.getTotalNum());

            //提鸡券
            QueryWrapper<ChickenCoupon> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", order.getCouponId());
            ChickenCoupon chickenCoupon = chickenCouponMapper.selectOne(queryWrapper);
            vo.setCouponName(chickenCoupon.getTitle());
            // 待收货状态
            if (CalcuUtils.getInstance().isEquals(order.getOrderStatus(), OrderStatusEnums.HAS_SEND.getId())) {
                //计算支付截止时间
                QueryWrapper<InfoShopping> wrapper = new QueryWrapper<>();
                InfoShopping infoShopping = iInfoShoppingService.getOne(wrapper);
                Date autoReceiveTime = DateUtil.getInstance().addDate(order.getSendTime(), infoShopping.getAutoReceived());
                vo.setAutoReceiveTime(autoReceiveTime);
            }
            List<OrderReceivedVo> receivedList = new ArrayList<>();
            QueryWrapper<OrderExpDetail> expWrapper = new QueryWrapper<>();
            expWrapper.eq("order_code", vo.getOrderCode());
            List<OrderExpDetail> expDetailList = orderExpDetailService.list(expWrapper);
            for (OrderExpDetail expDetail : expDetailList) {
                OrderReceivedVo receivedVo = new OrderReceivedVo();
                // 物流信息
                vo.setReceiver(expDetail.getReceiver());
                vo.setReceiverPhone(expDetail.getPhone());
                vo.setReceiverAddr(expDetail.getAddrPrefix() + " " + expDetail.getAddressDetail());
                if (order.getOrderStatus() >= OrderStatusEnums.HAS_SEND.getId()) {
                    receivedVo.setExpId(expDetail.getId());
                    // 最新的物流数据
                    String expMsg = orderExpDetailService.handleLiveExpData(expDetail.getId());
                    // 获取最近的物流时间和物流事件
                    getAcceptExp(receivedVo, expMsg);
                    receivedList.add(receivedVo);
                }
            }
            vo.setReceivedList(receivedList);

        }
        return vo;
    }

    @Override
    public ChickenLogisticsOrderDetailVo handleGetChickenOrderDetail(Integer orderId) {
        ChickenLogisticsOrder order = chickenLogisticsOrderMapper.selectById(orderId);
        ChickenLogisticsOrderDetailVo vo = new ChickenLogisticsOrderDetailVo();
        if (order != null) {
            BeanUtils.copyProperties(order, vo);
            // 待收货状态
            if (CalcuUtils.getInstance().isEquals(order.getOrderStatus(), OrderStatusEnums.HAS_SEND.getId())) {
                //计算支付截止时间
                QueryWrapper<InfoShopping> wrapper = new QueryWrapper<>();
                InfoShopping infoShopping = iInfoShoppingService.getOne(wrapper);
                Date autoReceiveTime = DateUtil.getInstance().addDate(DateUtil.getInstance().localDateTimeToDate(order.getSendTime()), infoShopping.getAutoReceived());
                vo.setAutoReceiveTime(autoReceiveTime);
            }

            List<OrderReceivedVo> receivedList = new ArrayList<OrderReceivedVo>();
            QueryWrapper<OrderExpDetail> expWrapper = new QueryWrapper<OrderExpDetail>();
            expWrapper.eq("order_code", vo.getOrderCode());
            List<OrderExpDetail> expDetailList = orderExpDetailService.list(expWrapper);
            for (OrderExpDetail expDetail : expDetailList) {
                OrderReceivedVo receivedVo = new OrderReceivedVo();
                // 物流信息
                vo.setReceiver(expDetail.getReceiver());
                vo.setReceiverPhone(expDetail.getPhone());
                vo.setReceiverAddr(expDetail.getAddrPrefix() + " " + expDetail.getAddressDetail());
                if (order.getOrderStatus() >= OrderStatusEnums.HAS_SEND.getId()) {
                    receivedVo.setExpId(expDetail.getId());
                    // 最新的物流数据
                    String expMsg = orderExpDetailService.handleLiveExpData(expDetail.getId());
                    // 获取最近的物流时间和物流事件
                    getAcceptExp(receivedVo, expMsg);
                    receivedList.add(receivedVo);
                }
            }
            vo.setReceivedList(receivedList);
            // 店铺联系信息
            BBusiness business = bBusinessService.getById(order.getBid());
            if (business != null) {
                vo.setbPhone(business.getPhone());
            }
        }
        return vo;
    }

    /**
     * 获取最近一条物流信息
     *
     * @param receivedVo 订单详情信息——接收物流信息
     * @param expMsg     物流信息JSON
     */
    public void getAcceptExp(OrderReceivedVo receivedVo, String expMsg) {
        String acceptTime = "";
        String acceptStation = "暂无物流信息";
        if (!StringUtils.isEmpty(expMsg)) {
            try {
                JSONArray array = JSONArray.parseArray(expMsg);
                if (array != null && array.size() > 0) {
                    JSONObject accept = array.getJSONObject(array.size() - 1);
                    acceptTime = accept.getString("time");
                    acceptStation = accept.getString("remark");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        receivedVo.setAcceptTime(acceptTime);
        receivedVo.setAcceptStation(acceptStation);
    }

    @Override
    public RestResponse deleteOrder(Integer cid, String orderCode) {
        OrderMain order = orderMainService.getByOrderCode(orderCode);
        if (!CalcuUtils.getInstance().isEquals(cid, order.getCid())) {
            return GetRest.getFail("订单数据有误");
        }
        if (OrderStatusEnums.CANCEL.getId().equals(order.getOrderStatus()) ||
                order.getOrderStatus().equals(OrderStatusEnums.OVER.getId())) {
            order.setDel(StaticUtils.STATUS_YES);
            boolean result = orderMainService.updateById(order);
            if (result) {
                return GetRest.getSuccess("删除成功");
            }
        } else {
            return GetRest.getFail("当前订单状态不可执行此操作");
        }
        return GetRest.getFail("删除失败");
    }

    @Override
    public RestResponse cancelOrder(Integer cid, String orderCode) {
        OrderMain order = orderMainService.getByOrderCode(orderCode);
        if (!CalcuUtils.getInstance().isEquals(cid, order.getCid())) {
            return GetRest.getFail("订单数据有误");
        }

        order.setOrderStatus(OrderStatusEnums.CANCEL.getId());
        order.setCancelTime(new Date());
        boolean result = orderMainService.updateById(order);
        if (result) {
            return GetRest.getSuccess("取消成功");
        }
        return GetRest.getFail("取消失败");
    }

    @Override
    public RestResponse handleOrderRemind(Integer cid, String orderCode) {
        OrderMain order = orderMainService.getByOrderCode(orderCode);
        if (!CalcuUtils.getInstance().isEquals(cid, order.getCid())) {
            return GetRest.getFail("订单数据有误");
        }

        if (!CalcuUtils.getInstance().isEquals(OrderStatusEnums.NEED_SEND.getId(), order.getOrderStatus())) {
            return GetRest.getFail("当前订单状态不可执行此操作");
        }
        // 如果不等于未提醒发货
        if (CalcuUtils.getInstance().isEquals(StaticUtils.STATUS_YES, order.getRemindSend())) {
            return GetRest.getFail("您已提醒发货");
        }
        order.setRemindSend(StaticUtils.STATUS_YES);
        boolean result = orderMainService.updateById(order);
        if (result) {
            return GetRest.getSuccess("提醒卖家发货成功");
        } else {
            return GetRest.getFail("提醒卖家发货失败");
        }
    }

    @Override
    public RestResponse handleOrderReceive(Integer cid, String orderCode) {
        OrderMain order = orderMainService.getByOrderCode(orderCode);
        if (!CalcuUtils.getInstance().isEquals(cid, order.getCid())) {
            return GetRest.getFail("订单数据有误");
        }
        if (!CalcuUtils.getInstance().isEquals(OrderStatusEnums.HAS_SEND.getId(), order.getOrderStatus())) {
            return GetRest.getFail("当前订单状态不可执行此操作");
        }
        QueryWrapper<OrderDetail> wrapper = new QueryWrapper<>();
        wrapper.eq("order_code", orderCode).eq("refund", StaticUtils.STATUS_APPLY);
        int count = orderDetailService.count(wrapper);
        if (count > 0) {
            return GetRest.getFail("当前订单包含正在退款中的商品，无法确认收货");
        }
        order.setReceivedTime(new Date());
        if (CalcuUtils.getInstance().isEquals(order.getOrderType(), OrderTypeEnums.LOGISTICS.getId())) {
            order.setOrderStatus(OrderStatusEnums.OVER.getId());
        } else {
            order.setOrderStatus(OrderStatusEnums.RECEIVED.getId());
        }
        boolean result = orderMainService.updateById(order);
        if (result) {
            QueryWrapper<OrderDetail> detailQueryWrapper = new QueryWrapper<>();
            detailQueryWrapper.eq("order_code", orderCode);
            List<OrderDetail> list = iOrderDetailService.list(detailQueryWrapper);
            for (int i = 0; i < list.size(); i++) {
                Integer detailid = list.get(i).getId();
                //解冻用户、商家、代理对应的冻结余额
                accountChangeService.handleFreezeCustomerMoney(new FreezeDTO(FreezeStatusEnums.SEND.getId(), detailid, 2));
                accountChangeService.handleFreezeBusinessMoney(new FreezeDTO(FreezeStatusEnums.SEND.getId(), detailid, 2));
                accountChangeService.handleFreezeAgentMoney(new FreezeDTO(FreezeStatusEnums.SEND.getId(), detailid, 2));
            }
            return GetRest.getSuccess("收货成功");
        } else {
            return GetRest.getFail("收货失败");
        }
    }

    @Override
    public RestResponse handleOrderEvaluate(Integer cid, OrderEvaluateVo vo) {
        OrderMain order = orderMainService.getByOrderCode(vo.getOrderCode());
        if (!CalcuUtils.getInstance().isEquals(cid, order.getCid())) {
            return GetRest.getFail("订单数据有误");
        }
        // 已收货后可以评价
        if (!CalcuUtils.getInstance().isEquals(OrderStatusEnums.RECEIVED.getId(), order.getOrderStatus())) {
            return GetRest.getFail("当前订单状态不可执行此操作");
        }

        // 评论信息
        Integer[] detailIds = vo.getDetailIds();
        Integer[] grades = vo.getGrades();
        List<String> urls = vo.getUrls();
        if (detailIds == null || detailIds.length < 1 || grades == null || grades.length < 1) {
            return GetRest.getFail("给个评分吧");
        }
        if (detailIds.length != grades.length) {
            return GetRest.getFail("给个评分吧");
        }
        // 判断评论
        if (vo.getContents() == null || vo.getContents().length() < 1) {
            return GetRest.getFail("请输入评论内容");
        }
        List<String> contents = Arrays.asList(vo.getContents().split("&"));
        if (contents == null || contents.size() <= 0 || detailIds.length != contents.size()) {
            return GetRest.getFail("请输入评论内容");
        }
        // 保存评价信息
        for (int i = 0; i < detailIds.length; i++) {
            Integer detailid = detailIds[i];
            Integer grade = grades[i];
            if (detailid == null || grade == null) {
                throw new ThrowJsonException("给个评分吧");
            }
            OrderDetail orderDetail = orderDetailService.getById(detailid);
            String content = contents.get(i);
            // 校验评价内容
            if (!StringUtils.isEmpty(content)) {
                if (content.length() > 100) {
                    throw new ThrowJsonException("内容包含违规字符或超过100个字");
                }
            } else {
                throw new ThrowJsonException("内容包含违规字符或超过100个字");
            }
            String url = "";
            if (urls != null && urls.size() > 0) {
                try {
                    url = urls.get(i);
                    url = url.replace("&", ",");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            ProcEvaluate procEvaluate = new ProcEvaluate();
            procEvaluate.setBid(order.getBid());
            procEvaluate.setCid(cid);
            procEvaluate.setProId(orderDetail.getProId());
            procEvaluate.setOrderId(order.getId());
            procEvaluate.setDetailId(orderDetail.getId());
            procEvaluate.setSpecName(orderDetail.getProSpecName());
            procEvaluate.setGrade(grade);
            procEvaluate.setContent(content);
            procEvaluate.setEvaluateUrl(url);
            if (!StringUtils.isEmpty(url)) {
                procEvaluate.setHasPhoto(StaticUtils.STATUS_YES);
            }
            Integer hide = vo.getHides()[i];
            procEvaluate.setHide(hide);
            procEvaluateMapper.insert(procEvaluate);
        }
        // 修改订单状态
        order.setOrderStatus(OrderStatusEnums.OVER.getId());
        order.setEvaluateTime(new Date());
        order.setOverTime(new Date());
        orderMainMapper.updateById(order);
        return GetRest.getSuccess("评论成功");
    }

    @Override
    public IPage<ProGroupVo> queryProGroupList(BasePage<ProGroupVo> page, String proCode) {
        IPage<ProGroupVo> pageInfo = orderConfigGroupMapper.queryProGroupList(page, proCode);
        for (ProGroupVo vo : pageInfo.getRecords()) {
            // 处理——拼团还差多少人
            QueryWrapper<OrderConfigGroup> wrapper = new QueryWrapper<OrderConfigGroup>();
            wrapper.eq("group_code", vo.getGroupCode()).ne("status", GroupStatusEnums.GROUP_CREATE.getId());
            int joinNum = orderConfigGroupMapper.selectCount(wrapper);
            vo.setSxNum(vo.getGroupNum() - joinNum);
        }
        return pageInfo;
    }

    @Override
    public Map<String, Object> queryGroupCusByGroupCode(String groupCode, Integer cid) {
        // 拼团结束时间
        QueryWrapper<OrderConfigGroup> wrapper = new QueryWrapper<OrderConfigGroup>();
        wrapper.eq("group_code", groupCode).eq("leader", StaticUtils.STATUS_YES);
        OrderConfigGroup configGroup = orderConfigGroupMapper.selectOne(wrapper);
        if (configGroup == null) {
            throw new ThrowJsonException("数据有误");
        }
        Map<String, Object> map = new HashMap<String, Object>();
        if (cid != null) {
            Integer groupLeader = StaticUtils.STATUS_NO;
            if (CalcuUtils.getInstance().isEquals(cid, configGroup.getCid())) {
                groupLeader = StaticUtils.STATUS_YES;
            }
            map.put("groupLeader", groupLeader);
        }
        int sxNum = 0;
        // 查询团购人数
        List<GroupCusVo> groups = orderConfigGroupMapper.queryGroupCusByGroupCode(groupCode);
        groups.forEach(group -> group.setCid(null));
        map.put("groupCus", groups);
        // 查询拼团信息
        ProGroupVo groupLeaderMsg = orderConfigGroupMapper.getGroupMsgByGroupCode(groupCode);
        // 处理——拼团还差多少人
        if (groups != null && groups.size() > 0) {
            sxNum = groups.get(0).getGroupNum() - groups.size();
        }
        groupLeaderMsg.setSxNum(sxNum);

        map.put("groupLeaderMsg", groupLeaderMsg);
        map.put("sxNum", sxNum);
        map.put("overTime", configGroup.getOverTime());
        map.put("orderCode", configGroup.getOrderCode());
        map.put("groupCode", configGroup.getGroupCode());
        return map;
    }

}
